package com.yunyao.client.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yunyao.client.request.*;
import com.yunyao.client.response.DeptResponse;
import com.yunyao.client.response.OrgResponse;
import com.yunyao.client.response.ProjectResponse;
import com.yunyao.client.response.UserResponse;
import com.yunyao.common.utils.HttpUtils;
import com.yunyao.common.web.util.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author xingjishuai
 * @date 2024-10-12
 */
@Slf4j
@Service
public class MdmClientServiceImpl implements MdmClientService {

    private Map<String, String> getHeaders() {
        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("Content-Type", "application/json");
        headersMap.put("charset", "UTF-8");
        headersMap.put("usercode", "ycerp");
        headersMap.put("password", "ycerp");
        return headersMap;
    }

    @Value("${mdm.server.url}")
    private String mdmServerUrl;

    private static final String USER_LIST_URL = "/esbmule/services/query/ycerp_cha_mdm_ry";
    private static final String ORG_LIST_URL = "/esbmule/services/query/ycerp_cha_mdm_xxzz";
    private static final String DEPT_LIST_URL = "/esbmule/services/query/ycerp_cha_mdm_xxbm";

    private static final String ESB = "ESB";
    private static final String DATA = "DATA";
    private static final String P_UUID = "PUUID";
    private static final String DATA_INFO = "DATAINFO";
    private static final String SPLIT_PAGE = "SPLITPAGE";
    private static final String DATA_INFOS = "DATAINFOS";
    private static final String CURRENT_PAGE = "CURRENTPAGE";
    private static final String COUNT_PER_PAGE = "COUNTPERPAGE";
    private static final String TOTAL_PAGES = "TOTALPAGES";
    private static final String TOTAL_NUMBER = "TOTALNUMBER";


    @Override
    public PageResult<UserResponse> userPageList(UserRequest userRequest, PageRequest pageRequest) {
        try {
            String url = mdmServerUrl + USER_LIST_URL;
            String body = requestConvertBody(userRequest, pageRequest);
            log.info("请求地址：{}，请求体：{}", url, body);
            // 发送HTTP请求
            String result = HttpUtils.sendPost(url, getHeaders(), body);
            log.info("响应结果：{}", result);
            return responseConvertResult(result, UserResponse.class);
        } catch (Exception ex) {
            log.error("查询主数据用户列表异常", ex);
            return new PageResult<>();
        }
    }

    @Override
    public PageResult<OrgResponse> orgPageList(OrgRequest orgRequest, PageRequest pageRequest) {
        try {
            String url = mdmServerUrl + ORG_LIST_URL;
            String body = requestConvertBody(orgRequest, pageRequest);
            log.info("请求地址：{}，请求体：{}", url, body);
            // 发送HTTP请求
            String result = HttpUtils.sendPost(url, getHeaders(), body);
            log.info("响应结果：{}", result);
            return responseConvertResult(result, OrgResponse.class);
        } catch (Exception ex) {
            log.error("查询主数据组织列表异常", ex);
            return new PageResult<>();
        }
    }

    @Override
    public PageResult<DeptResponse> deptPageList(DeptRequest deptRequest, PageRequest pageRequest) {
        try {
            String url = mdmServerUrl + DEPT_LIST_URL;
            String body = requestConvertBody(deptRequest, pageRequest);
            log.info("请求地址：{}，请求体：{}", url, body);
            // 发送HTTP请求
            String result = HttpUtils.sendPost(url, getHeaders(), body);
            log.info("响应结果：{}", result);
            return responseConvertResult(result, DeptResponse.class);
        } catch (Exception ex) {
            log.error("查询主数据部门列表异常", ex);
            return new PageResult<>();
        }
    }

    @Override
    public PageResult<ProjectResponse> projectPageList(ProjectRequest projectRequest, PageRequest pageRequest) {
        try {
            String url = mdmServerUrl + DEPT_LIST_URL;
            String body = requestConvertBody(projectRequest, pageRequest);
            log.info("请求地址：{}，请求体：{}", url, body);
            // 发送HTTP请求
            String result = HttpUtils.sendPost(url, getHeaders(), body);
            log.info("响应结果：{}", result);
            return responseConvertResult(result, ProjectResponse.class);
        } catch (Exception ex) {
            log.error("查询主数据项目列表异常", ex);
            return new PageResult<>();
        }
    }

    private <T> String requestConvertBody(T request, PageRequest pageRequest) {
        Long pageSize = pageRequest.getPageSize();
        Long pageIndex = pageRequest.getPageIndex();
        // 生成唯一请求标识
        String uuid = UUID.randomUUID().toString();
        // 校验请求对象是否为空
        if (request == null) {
            throw new IllegalArgumentException("Request cannot be null");
        }
        // 初始化ESB请求映射
        HashMap<String, Object> esbMap = new HashMap<>();
        // 初始化数据映射，用于存放分页信息和其他数据
        HashMap<String, Object> dataMap = new HashMap<>();
        // 初始化分页信息映射
        HashMap<String, String> splitPageMap = new HashMap<>();
        // 将每页数量和当前页码添加到分页信息映射中
        splitPageMap.put(COUNT_PER_PAGE, String.valueOf(pageSize));
        splitPageMap.put(CURRENT_PAGE, String.valueOf(pageIndex));
        // 将分页信息映射添加到数据映射中
        dataMap.put(SPLIT_PAGE, splitPageMap);
        // 初始化数据信息映射
        HashMap<String, Object> dataInfosMap = new HashMap<>();
        // 将请求对象添加到数据信息映射中，并设置PUUID为UUID
        dataInfosMap.put(DATA_INFO, Collections.singletonList(request));
        dataInfosMap.put(P_UUID, uuid);
        // 将数据信息映射添加到数据映射中
        dataMap.put(DATA_INFOS, dataInfosMap);
        // 将数据映射添加到ESB请求映射中
        esbMap.put(DATA, dataMap);
        // 初始化请求体Map，用于存放构建的请求数据
        HashMap<String, Object> bodyMap = new HashMap<>();
        // 创建并添加ESB相关的请求信息到请求体Map中
        bodyMap.put(ESB, esbMap);
        // 返回构建完成的请求体Map
        return JSON.toJSONString(bodyMap);
    }

    /**
     * 将响应结果转换为分页结果对象
     *
     * @param result 响应结果的JSON字符串
     * @param clazz 泛型类，用于解析数据对象
     * @param <T> 泛型参数类型
     * @return 转换后的分页结果对象
     */
    private <T> PageResult<T> responseConvertResult(String result, Class<T> clazz) {
        // 解析响应结果中的数据部分
        JSONObject dataResult = dataResult(result);
        if (dataResult == null) {
            return new PageResult<>();
        }

        // 获取数据信息的JSON对象
        JSONObject dataInfosJson = dataResult.getJSONObject(DATA_INFOS);
        if (dataInfosJson == null) {
            return new PageResult<>();
        }

        // 将数据信息解析为指定类类型的列表
        List<T> list = JSON.parseArray(dataInfosJson.getString(DATA_INFO), clazz);

        // 获取分页信息
        JSONObject splitPage = dataResult.getJSONObject(SPLIT_PAGE);
        if (splitPage == null) {
            return new PageResult<>();
        }

        // 提取分页信息
        String currentPage = splitPage.getString(CURRENT_PAGE);
        String countPerPage = splitPage.getString(COUNT_PER_PAGE);
        String totalPages = splitPage.getString(TOTAL_PAGES);
        String totalNumber = splitPage.getString(TOTAL_NUMBER);

        // 构造并返回结果对象
        return new PageResult<>(list, Long.parseLong(currentPage),
                Long.parseLong(countPerPage), Long.parseLong(totalPages),
                Long.parseLong(totalNumber));
    }

    private JSONObject dataResult(String result) {
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(result);
        JSONObject esbJson = jsonObject.getJSONObject(ESB);

        // 获取数据部分
        return esbJson.getJSONObject(DATA);
    }
}
